package com.mjf.web.controller.common;

import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mjf.cjt.Constants;
import com.mjf.cjt.MsgType;
import com.mjf.cjt.config.OpenApiConfig;
import com.mjf.cjt.domain.ChanjetEncryptMsg;
import com.mjf.cjt.event.ChanjetMsg;
import com.mjf.cjt.event.MsgEvent;
import com.mjf.cjt.event.content.AppTicketContent;
import com.mjf.cjt.event.content.TempAuthCodeContent;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.CjtAuthService;
import com.mjf.cjt.util.AESUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * @Authror pm
 * @Desc
 * @Date 2024-9-26 14:14
 */
@RestController
@RequestMapping("/api/Message")
@Api(tags = "畅捷通自由获取接口（勿动）")
public class ReceiveMsgFromCjtController {

    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    private OpenApiConfig appConfig;
    @Autowired
    private AsyncTMService asyncTMService;
    @Autowired
    private CjtAuthService cjtAuthService;


    /**
     * 生产加工单
     * @return
     * @throws ChanjetApiException
     */
    @GetMapping(value="/scjgd")
    public Object asyncC(@RequestParam(required = false) String start,@RequestParam(required = false) String end) throws ChanjetApiException {
        return asyncTMService.getSaleDeliveryOrderFromRemote(start, end);
    }

    @GetMapping(value="/code")
    public Object getCode(@RequestParam String code,@RequestParam(required = false) String state) throws ChanjetApiException {
        //通过临时code请求token，保存永久客户编码
        cjtAuthService.doTokenByTempCode(code);
        return code;
    }

    @PostMapping(value = "/Receive")
    public Object receive(@RequestBody ChanjetEncryptMsg chanjetEncryptMsg)  {
        Map<String, String> responseMap = new HashMap<>();
        try {
            String encryptMsg = chanjetEncryptMsg.getEncryptMsg();
//            log.info("解密前的消息{}", encryptMsg);
            String msg = AESUtils.aesDecrypt(encryptMsg, appConfig.getSecret());
//            log.info("解密后消息{}", msg);

            Map map = new Gson().fromJson(msg, Map.class);
            String msgType = (String) map.get(Constants.MSG_TYPE);

            //appKey不匹配返回fail
            if (!appConfig.getAppKey().equals(map.get(Constants.APP_KEY))) {
                responseMap.put(Constants.RESULT, Constants.FAIL);
                return responseMap;
            }

            //直接返回结果
            return execute(msg, msgType);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解析消息失败");
            responseMap.put(Constants.RESULT, Constants.FAIL);
            return responseMap;
        }
    }
    /**
     * 执行方法，使用spring的事件机制，将不同类型的事件分发到各个Handler进行执行
     *
     * @param msg     消息体
     * @param msgType 消息类型
     * @return
     */
    private Object execute(String msg, String msgType) {
        Map<String, String> responseMap = new HashMap<>();
        switch (msgType) {
            case MsgType.APP_TICKET:
                Type appTicketType = new TypeToken<ChanjetMsg<AppTicketContent>>() {
                }.getType();
                ChanjetMsg<AppTicketContent> appTicketMsg = new Gson().fromJson(msg, appTicketType);
                //发布事件，异步执行
                applicationContext.publishEvent(new MsgEvent(applicationContext, appTicketMsg));
                responseMap.put(Constants.RESULT, Constants.SUCCESS);
                return responseMap;
            case MsgType.TEMP_AUTH_CODE:
                Type tempAuthCodeType = new TypeToken<ChanjetMsg<TempAuthCodeContent>>() {
                }.getType();
                ChanjetMsg<TempAuthCodeContent> tempAuthCodeMsg = new Gson().fromJson(msg, tempAuthCodeType);
                //发布事件，异步执行
                applicationContext.publishEvent(new MsgEvent(applicationContext, tempAuthCodeMsg));
                responseMap.put(Constants.RESULT, Constants.SUCCESS);
                return responseMap;
            default:
                responseMap.put(Constants.RESULT, Constants.SUCCESS);
                System.out.println("沙箱验证，{}" + responseMap);
                return responseMap;
        }
    }
}
